package fr.uniscol.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadUtils {
	
	public static Map<String, Object> getUploadedFileFromRequest(HttpServletRequest request, String dir) 
	throws Exception{
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		Map<String, Object> results = new HashMap<String, Object>();
		
		List<FileItem> items = upload.parseRequest(request);
		for(FileItem fi : items){
			
			if(fi.isFormField()){
				results.put(fi.getFieldName(), fi.getString());
			}else{
				if(!fi.getName().equals("")){
					// Fichier 
					new File(dir).mkdirs();
					File tmp = new File(dir + System.getProperty("file.separator") + fi.getName());
					fi.write(tmp);
					
					results.put(fi.getFieldName(), tmp);
				}
			}
		}
		return results;
	}
}
